package capaDatos;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import utiles.UIDGenerator;

import capaLogica.Mensaje;
import capaLogica.Usuario;


public class UsuarioDAO {

	/**
	 * Atributo que crea la conexion a la bd
	 */
	private Connection conn;
	
	/**
	 * Constructor de la clase
	 */
	public UsuarioDAO(){
		conn = (Connection) ConnectionManager.getInstance().checkOut();
	}
	
	@Override
	 protected void finalize() {
       ConnectionManager.getInstance().checkIn(conn);
	}
	public boolean comprobarLogin(String nick, String password){
		boolean res = false;
		        PreparedStatement stmt = null;
		        ResultSet result = null;
		        String sql = "SELECT * FROM usuario WHERE ( nick = ? )";

		        try {
		            stmt = conn.prepareStatement(sql);
		            stmt.setString(1, nick);
		            result = stmt.executeQuery();
		            if ( result.next() ){
		            	if ( password.equals(result.getString("password")) ){
		            		res = true;
		            	}
		            }
		            
		        } catch (SQLException e) {
		            System.out.println("Message: " + e.getMessage());
		            System.out.println("SQLState: " + e.getSQLState());
		            System.out.println("ErrorCode: " + e.getErrorCode());
		        } finally {
		            try {
		                if (result != null) {
		                    result.close();
		                }
		                if (stmt != null) {
		                    stmt.close();
		                }
		            } catch (SQLException e) {
		            }
		        }
		return res;
	}
	
	 public Usuario recuperarUsuarioByIdUsuario(String idUsuario) {
	        PreparedStatement stmt = null;
	        ResultSet result = null;
	        Usuario u = null;
	        String sql = "SELECT * FROM usuario WHERE (idUsuario = ?) ";

	        try {
	            stmt = conn.prepareStatement(sql);
	            stmt.setString(1, idUsuario);
	            result = stmt.executeQuery();

	            result.next();
	            u = new Usuario();
	            u.setIdUsuario(result.getString("idUsuario"));
	            u.setNick(result.getString("nick"));
	            u.setPassword(result.getString("password"));
	            u.setIdTipo(result.getString("idTipo"));
	            u.setIdPerfil(result.getString("idPerfil"));
	            u.setFechaRegistro(result.getDate("fechaRegistro"));
	            u.setUltimaConexion(result.getDate("ultimaConexion"));
	            u.setAdmin(result.getString("admin"));
	            
	        } catch (SQLException e) {
	            System.out.println("Message: " + e.getMessage());
	            System.out.println("SQLState: " + e.getSQLState());
	            System.out.println("ErrorCode: " + e.getErrorCode());
	        } finally {
	            try {
	                if (result != null) {
	                    result.close();
	                }
	                if (stmt != null) {
	                    stmt.close();
	                }
	            } catch (SQLException e) {
	            }
	        }
	        return u;
	    }

	public Usuario insertarUsuario(Usuario user) {
		String sql = "INSERT INTO usuario (idUsuario,nick,password,idTipo,idPerfil,fechaRegistro,ultimaConexion,admin) VALUES (?,?,?,?,?,?,?,?) ";
		PreparedStatement stmt = null;
		
		try {
			stmt = conn.prepareStatement(sql);
			user.setIdUsuario(UIDGenerator.getInstance().getKey());
			
			stmt.setString(1, user.getIdUsuario());
			stmt.setString(2, user.getNick());
			stmt.setString(3, user.getPassword());
			stmt.setString(4, user.getIdTipo());
			stmt.setString(5, "");
			stmt.setDate(6, (Date) user.getFechaRegistro());
			stmt.setDate(7, (Date) user.getUltimaConexion());
			stmt.setString(8, user.getAdmin());
		
			stmt.executeUpdate();

		} catch (SQLException e) {
			System.out.println("Message: " + e.getMessage());
			System.out.println("SQLState: " + e.getSQLState());
			System.out.println("ErrorCode: " + e.getErrorCode());
		} finally {
			try {
				if (stmt != null) {
					stmt.close();
					
				}
			} catch (SQLException e) {
			}
		}
		
		return user;
	}

	public void actualizarUsuario(Usuario u) {
		String sql = "UPDATE usuario SET nick = ?, password = ?, idTipo = ?, idPerfil = ?, fechaRegistro = ? ,ultimaConexion = ? WHERE (idUsuario = ?)";
		PreparedStatement stm = null;
		try {
			stm = conn.prepareStatement(sql);
			stm.setString(1, u.getNick());
			stm.setString(2, u.getPassword());
			stm.setString(3, u.getIdTipo());
			stm.setString(4, u.getIdPerfil());
			stm.setDate(5, (Date) u.getFechaRegistro());
			stm.setDate(6, (Date) u.getUltimaConexion());
			stm.setString(7, u.getIdUsuario());
			stm.executeUpdate();

		} catch (SQLException e) {
			System.out.println("Message: " + e.getMessage());
			System.out.println("SQLState: " + e.getSQLState());
			System.out.println("ErrorCode: " + e.getErrorCode());
		} finally {
			try {
				if (stm != null) {
					stm.close();
				}
			} catch (SQLException e) {

			}
		}
	}
	
	public Usuario recuperarUsuarioByNick(String nick){
		  PreparedStatement stmt = null;
	        ResultSet result = null;
	        Usuario u = new Usuario();
	        String sql = "SELECT * FROM usuario WHERE (nick = ?) ";

	        try {
	            stmt = conn.prepareStatement(sql);
	            stmt.setString(1, nick);
	            result = stmt.executeQuery();

	            if ( result.next() ){
	            	 u = new Usuario();
	 	            u.setIdUsuario(result.getString("idUsuario"));
	 	            u.setNick(result.getString("nick"));
	 	            u.setPassword(result.getString("password"));
	 	            u.setIdTipo(result.getString("idTipo"));
	 	            u.setIdPerfil(result.getString("idPerfil"));
	 	            u.setFechaRegistro(result.getDate("fechaRegistro"));
	 	            u.setUltimaConexion(result.getDate("ultimaConexion"));
	 	            u.setAdmin(result.getString("admin"));
	            }
	        } catch (SQLException e) {
	            System.out.println("Message: " + e.getMessage());
	            System.out.println("SQLState: " + e.getSQLState());
	            System.out.println("ErrorCode: " + e.getErrorCode());
	        } finally {
	            try {
	                if (result != null) {
	                    result.close();
	                }
	                if (stmt != null) {
	                    stmt.close();
	                }
	            } catch (SQLException e) {
	            }
	        }
	        return u;
	} 

	public List<String> recuperarFavoritos(String idUsuarios){
		  PreparedStatement stmt = null;
	        ResultSet result = null;
	        List<String> listaIdUsuarioFavoritos = new ArrayList<String>();
	        String sql = "SELECT * FROM favorito WHERE (idUsuario = ?) ";

	        try {
	            stmt = conn.prepareStatement(sql);
	            stmt.setString(1, idUsuarios);
	            result = stmt.executeQuery();

	            if ( result.next() ){
	            	listaIdUsuarioFavoritos = new ArrayList<String>();
	            	listaIdUsuarioFavoritos.add(result.getString("idUsuario"));
	            }
	        } catch (SQLException e) {
	            System.out.println("Message: " + e.getMessage());
	            System.out.println("SQLState: " + e.getSQLState());
	            System.out.println("ErrorCode: " + e.getErrorCode());
	        } finally {
	            try {
	                if (result != null) {
	                    result.close();
	                }
	                if (stmt != null) {
	                    stmt.close();
	                }
	            } catch (SQLException e) {
	            }
	        }
	        return listaIdUsuarioFavoritos;
	} 
	
	public void recomendarUsuario(Mensaje m) {
		String sql = "INSERT INTO mensaje (idMensaje,idUserCreador,idUserReceptor,descripcion,fechaPublicacion,leido,recomendado) VALUES (?,?,?,?,?,?,?) ";
		PreparedStatement stmt = null;
		
		try {
			stmt = conn.prepareStatement(sql);
			
			stmt.setString(1, UIDGenerator.getInstance().getKey());
			stmt.setString(2, m.getIdUsuarioCreador());
			stmt.setString(3, m.getIdUsuarioReceptor());
			stmt.setString(4, m.getDescripcion());
			stmt.setDate(5, (Date) m.getFechaPublicacion());
			stmt.setString(6, m.getLeido());
			stmt.setString(7, m.getRecomendaciones());
		
			stmt.executeUpdate();

		} catch (SQLException e) {
			System.out.println("Message: " + e.getMessage());
			System.out.println("SQLState: " + e.getSQLState());
			System.out.println("ErrorCode: " + e.getErrorCode());
		} finally {
			try {
				if (stmt != null) {
					stmt.close();
					
				}
			} catch (SQLException e) {
			}
		}
	}
	
}
